#coding:utf-8
__author__ = 'Administrator'
import smtplib
import base64

#通过STML邮件协议验证邮箱
class UserEmail:
    name = ''
    pwd = ''
    server_tag=''
    server=None

    def __init__(self,name,pwd):
        self.name = name
        self.pwd = pwd

        self.server_tag = self.name.split('@')[1].upper()
        if '163' in self.server_tag:
            self.server = smtplib.SMTP('smtp.163.com')
        #QQ邮箱默认关闭smtp服务
        elif 'QQ' in self.server_tag:
            self.server = smtplib.SMTP('smtp.qq.com',25)
        elif 'SINA' in self.server_tag:
            self.server = smtplib.SMTP('smtp.sina.com')
        elif '126' in self.server_tag:
            self.server = smtplib.SMTP('smtp.126.com')

    def login(self):
        '''
        from_user = self.name
        to_user = '545127804@qq.com'

        msg = '你好，朋友'
        '''
        print(self.name,self.pwd)
        print(self.server_tag)
        self.server.set_debuglevel(1)
        try:
           self.server.login(self.name,self.pwd)
           print('success')
        except:
           print('fail')
        finally:
           self.server.close()

        '''
        #debug模式
        #self.server.set_debuglevel(1)
        #ehlo命令，docmd方法包括了获取对方服务器返回信息
        self.server.docmd('EHLO server')
        #auth login命令
        self.server.docmd('AUTH LOGIN')
        #发送用户名和密码，经过base64编码，通过getreply获取返回信息
        self.server.send(base64.encodestring(self.name))
        self.server.getreply()
        self.server.send(base64.encodestring(self.pwd))
        result = self.server.getreply()
        if 'successful' in str(result):
             #发送邮件发送者和接收者
            self.server.docmd('MAIL FROM:<%s>'%from_user)
            self.server.docmd('RCPT TO:<%s>'%to_user)
            #发送数据
            self.server.docmd("DATA")
            #发送正文吧
            self.server.send(msg)
            #结束标志
            self.server.send('.')
            self.server.getreply()
            #发送结束，退出
            self.server.quit()
            print('发送成功')
        else:
            print('登录失败')

        '''


#使用测试
if __name__ == '__main__':
  user = UserEmail('13529085@163.com','m8382117')
  user.login()

  user2 = UserEmail('13526519085@163.com','8382117')
  user2.login()

  user1 = UserEmail('545127804@qq.com','wo94bufo!')
  user1.login()


